$(document).ready(function() {
	projectSearchListener();
	alertCloseListener();
	ajaxListener();
});

function projectSearchListener(){
	$("#projectSearchButton").click(function(event) {
		event.preventDefault();
		var valid = bsValidateLength($("#id"), 6);
		if (valid) {
			$.ajax({
				type : "POST",
				url : "../project/search",
				data : $("#searchForm").serialize(),
				success : function(project) {
					console.log(project);
					var tr = createTr([1,project.id,project.name,project.customerName,project.plannedStartDate,project.plannedEndDate,project.status]);
					$(tr).appendTo("#projectTable tbody");
					if(!project) {
						$("#errorText").html("<strong>Snap!</strong> Search params return no records. Please check whether the project id is correct.");
						$("#failureDiv").slideDown();
					}else {
						$("#projectTable").slideDown();
					}
				}
			});
		}
	});
}

function createTr(values){
	return encloseTds(createTd(values));
}

function createTd(values){
	var tds = "";
	for(var i=0;i<values.length;i++){
		tds=tds+"<td>"+values[i]+"</td>";
	}
	return tds;
}

function encloseTds(value){
	return "<tr>"+value+"</tr>";
}

function ajaxListener(){
	$(document).ajaxSend(function(event, request, settings) {
		$("#successDiv").hide();
		$("#failureDiv").hide();
		$("#qsTable tbody").html("");
		$("#qsTable").hide();
		$("#psTable tbody").html("");
		$("#psTable").hide();
		$("#liTable tbody").html("");
		$("#liTable").hide();
		$('#overlay').show();
		$('#loading-indicator').slideDown();
	});
	$(document).ajaxComplete(function(event, request, settings) {
		$('#overlay').hide();
		$('#loading-indicator').hide();
	});
}

function alertCloseListener(){
	$(".close").click(function(event) {
		event.preventDefault();
		$(this).parent().hide();
	});
}

function bsValidateLength(element, minLength) {
	element.closest("div .control-group").removeClass("error");
	element.parent().find(".help-inline").remove();
	if (element.val().length < minLength) {
		element.closest("div .control-group").addClass('error');
		element.parent().append(
				"<span class='help-inline'>Atleast " + minLength
						+ " characters expected!</span>");
		return false;
	} else {
		return true;
	}
}